//
//  HMComposePictureView.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/10/5.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
//自定义发送微博时的配图
class HMComposePictureView: UICollectionView {

    //点击最后一个cell执行的闭包
    var lastCellCallBack:(()->())?
    
    //记录选中的图片数据
    lazy var images:[UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setUpUI() {
        backgroundColor = UIColor.red
        //配图的默认状态为隐藏
        isHidden = true
        //设置数据源
        dataSource = self
        //设置代理
        delegate = self
        //注册cell
        register(HMComposePictureViewCell.self, forCellWithReuseIdentifier: "cell")
    }
    
    //添加图片的方法
    func addImage(image:UIImage) -> Void {
        //如果图片张数达到九张就不允许继续添加
        if images.count == 9 {
            return
        }
        
        //如果添加图片的话就显示配图
        isHidden = false
        
        images.append(image)
        //刷新数据
        reloadData()
    }
    
    //调整配图的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        //图片之间的间距
        let imageMargin:CGFloat = 5
        //每张图片的宽度
        let itemWidth = (width - 2 * imageMargin) / 3
        
        //每张图片的大小
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width:itemWidth,height:itemWidth)
        
        //图片之间垂直方向的间距
        flowLayout.minimumLineSpacing = imageMargin
        //图片之间水平方向的间距
        flowLayout.minimumInteritemSpacing = imageMargin
    }
}

//数据源方法
extension HMComposePictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //如果图片的张数等于0或9时不显示添加图片的加号
        if images.count == 0 || images.count == 9 {
            return images.count
        }else {
            //其余的显示添加图片的加号
            return images.count + 1
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMComposePictureViewCell
        //cell.backgroundColor = UIColor.green
        
        //如果是最后一个cell就不显示数组中的图片
        if indexPath.item == images.count {
            cell.image = nil
        }else{
            //其余的正常显示
            cell.image = images[indexPath.item]
            cell.indexPath = indexPath
            cell.deleteCallBack = {
                self.images.remove(at: indexPath.item)
                
                //如果没有添加图片就隐藏配图
                if self.images.count == 0 {
                    self.isHidden = true
                }
                
                //刷新数据
                self.reloadData()
            }
        }
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //如果点击的是最后一个cell，就打开图片浏览器
        if images.count == indexPath.item {
            lastCellCallBack?()
        }
    }
}

//发送微博配图的cell
class HMComposePictureViewCell:UICollectionViewCell {
    //执行删除的闭包
    var deleteCallBack:(()->())?
    //记录图片的indexPath
    var indexPath:IndexPath?
    
    //懒加载
    private lazy var imageView:UIImageView = UIImageView(image:UIImage(named:"timeline_image_placeholder"))
    //删除按钮
    private lazy var deleteButton:UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: #selector(deleteButtonClick), for: .touchUpInside)
        button.setImage(UIImage(named:"compose_photo_close"), for: .normal)
        return button
    }()
    
    //设置cell上显示的图片
    var image:UIImage? {
        didSet {
            if image == nil {
                //表示是最后一个cell，显示添加图片的加号按钮,不显示删除按钮
                imageView.image = UIImage(named:"compose_pic_add")
                deleteButton.isHidden = true
            }else{
                //其余的正常显示
              imageView.image = image
                deleteButton.isHidden = false
            }
            
        }
    }
    
    //删除按钮的点击事件
    @objc private func deleteButtonClick() {
        print("删除")
        deleteCallBack?()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件并设置约束
    private func setUpUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        
        deleteButton.snp_makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.right.equalTo(imageView)
        }
        
    }
}
